﻿using System;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web.UI.WebControls;
using Business;
using Common;
using Common.Constant;

public partial class User : System.Web.UI.Page
{
    private UsersBus _usersBus;
    private Entity.User _user;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["User"] != null)
            {
                LoadUserInfo(Session["User"].ToString());
            }
            else
            {
                Response.Redirect("~/Default.aspx");
            }
        }
        LoadEditor();
    }
    private void LoadEditor()
    {
        txtMoreInfo.ToolbarStartupExpanded = false;
        txtMoreInfo.config.toolbar = new object[]
			{
				new object[] { "Source", "-", "Save", "NewPage", "Preview", "-", "Templates" },
                new object[] { "Bold", "Italic", "Underline", "Strike", "-", "Subscript", "Superscript" },
                new object[] { "NumberedList", "BulletedList", "-", "Outdent", "Indent", "Blockquote", "CreateDiv" },
				"/",
				new object[] { "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock" },
				new object[] { "Link", "Unlink", "Anchor" },
				new object[] { "Image", "Flash", "Table", "HorizontalRule", "Smiley", "SpecialChar", "PageBreak", "Iframe" },
                new object[] { "BidiLtr", "BidiRtl" },
				"/",
				new object[] { "Styles", "Format", "Font", "FontSize" },
				new object[] { "TextColor", "BGColor" },
				new object[] { "Maximize", "ShowBlocks", "-", "About" }
			};
    }
    protected void BtnUploadClick(Object sender, EventArgs e)
    {
        UploadPhoto(fuPhoto);
    }
    protected void UploadPhoto(FileUpload fu)
    {
        if (fu.HasFile)
        {
            try
            {
                if (fu.PostedFile.ContentType == "image/jpeg" || fu.PostedFile.ContentType == "image/gif" || fu.PostedFile.ContentType == "image/png")
                {
                    if (fu.PostedFile.ContentLength < 4096000)
                    {
                        const int thumbWidth = 150;
                        const int thumbHeight = 110;

                        System.Drawing.Image oImg = System.Drawing.Image.FromStream(fu.PostedFile.InputStream);
                        System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);
                        System.Drawing.Image phoi = new Bitmap(Server.MapPath("~/resource/images/b.png"));

                        Graphics oGraphic = Graphics.FromImage(oThumbNail);
                        oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                        oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                        oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                        var oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                        oGraphic.DrawImage(oImg, oRectangle);
                        oGraphic.DrawImage(phoi, 120, 80);

                        string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
                        oThumbNail.Save(Server.MapPath("~/resource/upload/avatar/") + filename, ImageFormat.Jpeg);
                        oImg.Dispose();

                        txtPhoto.Text = "resource/upload/avatar/" + filename;
                        lblMessage.Text = UIMessage.UploadSuccess;
                        lblMessage.ForeColor = Color.Blue;
                    }
                    else
                        lblMessage.Text = UIMessage.MaxUploadSize;
                }
                else
                    lblMessage.Text = UIMessage.OnlyImageFileAccepted;
            }
            catch (Exception ex)
            {
                lblMessage.Text = UIMessage.UploadError + ex.Message;
            }
        }
    }
    protected void LoadUserInfo(string userName)
    {
        _usersBus = new UsersBus();
        DataSet userInfo = _usersBus.GetUserByUserName(userName);
        if(userInfo.Tables[0].Rows.Count>0)
        {
            txtName.Text = Session["User"].ToString();
            txtName.Enabled = false;
            txtPassword.Value = userInfo.Tables[0].Rows[0]["Password"].ToString();
            txtFullName.Text = userInfo.Tables[0].Rows[0]["FullName"].ToString();
            txtEmail.Text = userInfo.Tables[0].Rows[0]["Email"].ToString();
            txtPhoto.Text = userInfo.Tables[0].Rows[0]["AvatarPath"].ToString();
            txtDateOfBirth.Text = userInfo.Tables[0].Rows[0]["DateOfBirth"].ToString();
            txtMoreInfo.Text = userInfo.Tables[0].Rows[0]["MoreInfo"].ToString();
            drdCategory.SelectedIndex = userInfo.Tables[0].Rows[0]["IsAdmin"].ToString() == "True" ? 0 : 1;
            drdCategory.Enabled = false;
            btnSubmit.Text = "Lưu sửa đổi";
        }
    }
    protected void ButtonSubmitClick(object sender,EventArgs e)
    {
        try
        {
            if(btnSubmit.Text == "Lưu sửa đổi")
            {
                _user = new Entity.User
                            {
                                Password = txtPassword.Value,
                                FullName = txtFullName.Text,
                                UserName = txtName.Text,
                                IsAdmin = false,
                                Email = txtEmail.Text,
                                DateOfBirth = DateTime.Parse(txtDateOfBirth.Text),
                                AvatarPath = txtPhoto.Text,
                                MoreInfo = txtMoreInfo.Text
                            };
                _usersBus = new UsersBus();
                bool result = _usersBus.UpdateUser(_user);
                UIMessage.ShowMessage(result ? "Cập nhật thành công" : "Cập nhật thất bại", this);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
}
